<template>
  <el-container style="height: 100vh;
                      background-image: url('/img/bg.png'), linear-gradient(135deg, #1352f2, #3c82f5);
                      background-size: cover;
                      background-position: center;
                      background-repeat: no-repeat;
                      overflow: hidden;">
    <!-- 头部区域 -->
    <el-header style="padding: 20px 50px; height: auto; background: transparent;">
      <div class="header-container">
        <img src="/img/logo.png" class="header-logo" alt="达内教育">
        <img src="/img/verticalLine.png" class="header-divider" alt="分割线">
        <span class="header-title">LBS智慧营销管理系统</span>
      </div>
    </el-header>

    <!-- 主内容区域 -->
    <el-main style="padding: 0; display: flex; align-items: center; justify-content: center;">
      <!-- 登录卡片 -->
      <div class="login-card">
        <!-- 左侧图片区域 -->
        <div class="login-image">
          <img src="/img/login.png" alt="LBS系统" class="lbs-image">
        </div>

        <!-- 右侧表单区域 -->
        <div class="login-form-container">
          <el-form :model="user" label-position="top" size="default" class="login-form" ref="loginForm">
            <!-- 视角选择 -->
            <el-form-item>
              <el-select
                  v-model="viewType"
                  placeholder="请选择视角"
                  class="form-select"
                  @change="handleViewChange"
              >
                <el-option label="商家视角" value="merchant"></el-option>
                <el-option label="平台视角" value="platform"></el-option>
              </el-select>
            </el-form-item>

            <!-- 手机号输入 -->
            <el-form-item>
              <el-input
                  v-model="user.phone"
                  placeholder="请输入手机号"
                  :prefix-icon="Phone"
                  class="form-input"
                  maxlength="11"
                  @input="formatPhone"
              ></el-input>
            </el-form-item>

            <!-- 密码输入 -->
            <el-form-item>
              <el-input
                  v-model="user.password"
                  placeholder="请输入密码"
                  show-password
                  :prefix-icon="Lock"
                  class="form-input"
              ></el-input>
            </el-form-item>

            <!-- 验证码（后端生成） -->
            <el-form-item>
              <el-row :gutter="10" class="captcha-row">
                <el-col :span="14">
                  <el-input
                      v-model="user.captcha"
                      placeholder="请输入验证码"
                      :prefix-icon="Key"
                      class="form-input"
                  ></el-input>
                </el-col>
                <el-col :span="10">
                  <img
                      :src="captchaImageUrl"
                      class="captcha-image"
                      @click="getCaptcha"
                      alt="验证码"
                      :title="captchaLoading ? '加载中...' : '点击刷新'"
                  >
                </el-col>
              </el-row>
            </el-form-item>

            <!-- 登录按钮 -->
            <el-form-item>
              <el-button
                  type="primary"
                  class="login-button"
                  @click="handleLogin"
                  :loading="loginLoading"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, nextTick, getCurrentInstance } from "vue";
import { Phone, Lock, Key, Refresh } from '@element-plus/icons-vue';
import { ElMessage } from "element-plus";
import axios from "axios";
import router from '../router';

// 获取全局BASE_URL
const { proxy } = getCurrentInstance();
const BASE_URL = proxy.BASE_URL;

// 登录数据
const user = ref({
  phone: '19941253145',
  password: '',
  captcha: '',  // 用户输入的验证码
  captchaKey: ''  // 后端返回的验证码标识
});

// 视角选择
const viewType = ref('merchant');

// 验证码相关
const captchaImageUrl = ref('');
const captchaLoading = ref(false);

// 登录状态
const loginLoading = ref(false);

// 切换视角时刷新验证码
const handleViewChange = () => {
  getCaptcha();
};

// 获取后端验证码
const getCaptcha = () => {
  captchaLoading.value = true;
  // 映射视角到后端的viewType（0-商家，1-平台）
  const viewTypeMap = { merchant: 0, platform: 1 };
  axios.get(BASE_URL + '/v1/captcha/generate', {
    params: {
      viewType: viewTypeMap[viewType.value],
      timestamp: Date.now()
    },
    responseType: 'blob'
  }).then(response => {
    const blob = new Blob([response.data], { type: 'image/png' });
    nextTick(() => {
      captchaImageUrl.value = URL.createObjectURL(blob);
      user.value.captchaKey = response.headers['x-captcha-key']; // 从响应头获取标识
      captchaLoading.value = false;
    });
  }).catch(error => {
    console.error('获取验证码失败', error);
    ElMessage.error('验证码加载失败，请重试');
    captchaLoading.value = false;
  });
};

// 手机号格式化
const formatPhone = (val) => {
  user.value.phone = val.replace(/\s/g, '').replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3');
};

// 登录处理
const handleLogin = () => {
  if (!user.value.phone.trim()) {
    ElMessage.error('请输入手机号');
    return;
  }
  if (!user.value.password) {
    ElMessage.error('请输入密码');
    return;
  }
  if (!user.value.captcha) {
    ElMessage.error('请输入验证码');
    return;
  }
  if (!user.value.captchaKey) {
    ElMessage.error('请先获取验证码');
    return;
  }

  loginLoading.value = true;
  const loginUrl = viewType.value === 'platform'
      ? '/passport/admin/login'
      : '/passport/user/login';

  // 发送登录请求，携带验证码标识和输入值
  axios.post(BASE_URL + loginUrl, {
    phone: user.value.phone.replace(/\s/g, ''),
    password: user.value.password
  }, {
    params: {
      captcha: user.value.captcha  // 验证码输入值作为请求参数
    },
    headers: {
      'x-captcha-key': user.value.captchaKey  // 验证码标识作为请求头
    }
  }).then(response => {
    loginLoading.value = false;
    const { code, data, message } = response.data;
    if (code === 2000) {
      const { jwt: token, userInfo } = data;
      localStorage.setItem('token', token);
      localStorage.setItem('user', JSON.stringify(userInfo));
      localStorage.setItem('viewType', viewType.value);
      ElMessage.success('登录成功');
      router.push('/');
    } else {
      ElMessage.error(message || '登录失败');
      getCaptcha();
    }
  }).catch(error => {
    loginLoading.value = false;
    console.error('登录请求失败', error);
    ElMessage.error('网络异常，请稍后重试');
    getCaptcha();
  });
};

// 页面加载时获取验证码
onMounted(() => {
  getCaptcha();
});
</script>

<style scoped>
/* 顶部栏样式 */
.header-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-logo {
  height: 50px;
}

.header-divider {
  height: 35px;
  opacity: 0.8;
}

.header-title {
  font-size: 28px;
  color: #fff;
  font-weight: 500;
  letter-spacing: 0.5px;
}

/* 登录卡片样式 */
.login-card {
  display: flex;
  width: 820px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-top: 30px;
}

/* 左侧图片区域 */
.login-image {
  flex: 1;
  background-color: #f5f8ff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.lbs-image {
  width: 100%;
  max-width: 240px;
  object-fit: contain;
}

/* 右侧表单区域 */
.login-form-container {
  flex: 1.2;
  padding: 50px 40px;
}

.login-form {
  width: 100%;
}

/* 表单元素样式 */
.form-select, .form-input {
  width: 100%;
  height: 44px;
  border-radius: 4px;
}

/* 验证码图片样式 */
.captcha-row {
  width: 100%;
}

.captcha-image {
  width: 100%;
  height: 44px;
  border-radius: 4px;
  cursor: pointer;
  object-fit: cover;
  background-color: #f0f5ff;
  border: 1px solid #e1e6eb;
}

/* 登录按钮样式 */
.login-button {
  width: 100%;
  height: 46px;
  font-size: 16px;
  background-color: #1352f2;
  border-color: #1352f2;
  border-radius: 4px;
}

.login-button:hover {
  background-color: #0e46d2;
  border-color: #0e46d2;
}

/* 表单项间距调整 */
:deep(.el-form-item) {
  margin-bottom: 22px !important;
}

/* 输入框聚焦样式 */
:deep(.el-input__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 选择框样式 */
:deep(.el-select .el-input__inner) {
  height: 44px;
  line-height: 44px;
}

:deep(.el-select-dropdown__item.selected) {
  color: #1352f2;
}
</style>